package cn.edu.hbwe.book.servlet.client;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;

import cn.edu.hbwe.book.entity.Order;
import cn.edu.hbwe.book.entity.Product;
import cn.edu.hbwe.book.entity.User;
import cn.edu.hbwe.book.service.OrderService;
import cn.edu.hbwe.book.utils.IdUtils;
import cn.edu.hbwe.book.entity.OrderItem;

/**
 * 创建订单
 */
@WebServlet("/createOrder")
public class CreateOrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.封装订单数据到javabean
		Order order = new Order();
		try {
			BeanUtils.populate(order, request.getParameterMap());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//2.补全数据
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		Map<Product, Integer> cart = (Map<Product, Integer>)session.getAttribute("cart");		
		order.setUser(user);// 封装用户信息到订单.
		order.setId(IdUtils.getUUID());// 封装订单id
		//把对应的商品封装到订单条目,再把订单条目添加到订单
		for (Product p : cart.keySet()) {
			OrderItem item = new OrderItem();
			item.setOrder(order);
			item.setBuynum(cart.get(p));
			item.setP(p);
			order.getOrderItems().add(item);
		}
		//调用service生成订单
		OrderService service = new OrderService();
		service.addOrder(order);
		//订单生成成功。跳转到成功页面，回显数据
		response.sendRedirect(request.getContextPath() + "/client/createOrderSuccess.jsp");
		
	}

}
